package gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import model.ProcessType;
import model.Stack;
import model.TaskInfo;

public class TaskListDialog extends JDialog {

    private Stack stack;
    private JPanel contentPane = new JPanel();

    public TaskListDialog(Stack stack) {
	this.stack = stack;
	setContentPane(contentPane);
	getContentPane().setLayout(null);

	setTitle("Task list for " + this.stack.getProductType().getName());
	setResizable(false);

	setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

	setLocation(400, 200);
	setSize(400, 400);

	JButton btnOk = new JButton("OK");
	btnOk.setBounds(140, 340, 89, 23);
	btnOk.addActionListener(new ActionListener() {

	    @Override
	    public void actionPerformed(ActionEvent arg0) {
		dispose();
	    }
	});

	contentPane.add(new TaskListPanel());
	contentPane.add(btnOk);

    }

    private class TaskListPanel extends JPanel {

	protected JTable tbl;
	private DefaultTableModel model = new DefaultTableModel();
	protected Vector<String> columnNames = new Vector<String>();
	protected Vector<Vector<Object>> data = new Vector<Vector<Object>>();

	public TaskListPanel() {

	    setLayout(new BorderLayout(0, 0));

	    setSize(375, 300);
	    setLocation(10, 10);

	    tbl = new JTable(model) {
		@Override
		public boolean isCellEditable(int rowIndex, int colIndex) {
		    return false; // Disallow the editing of any cell
		}

	    };

	    JScrollPane scrollPane = new JScrollPane(tbl);

	    String[] columnNamesArray = { "Process name", "Start time",
		    "Finish time", "Takes places in" };

	    for (int i = 0; i < columnNamesArray.length; i++) {
		columnNames.add(columnNamesArray[i]);
	    }

	    generateDataVector();

	    setData(columnNames, data);

	    add(scrollPane, BorderLayout.CENTER);

	}

	protected void generateDataVector() {
	    for (TaskInfo x : TaskListDialog.this.stack.getTasks()) {
		Vector<Object> dataRow = new Vector<Object>();
		dataRow.add(x.getProcess().getName());
		dataRow.add(x.getStartTime());
		dataRow.add(x.getFinishTime());
		dataRow.add(x.getProcess().getProcessType() == ProcessType.IN_STOCK ? "In stock"
			: "Not in stock");
		data.add(dataRow);
	    }
	}

	public void setData(Vector<String> columnNames,
		Vector<Vector<Object>> data) {
	    this.columnNames = columnNames;
	    this.data = data;
	    DefaultTableModel newModel = new DefaultTableModel(this.data,
		    this.columnNames);
	    tbl.setModel(newModel);

	}
    }
}
